package com.example.demo.utils;

import java.util.HashMap;
import java.util.Map;

public class FileTypeInference {


    // 全局静态的 MIME 类型映射表
    private static final Map<String, String> MIME_TYPE_MAP = new HashMap<>();

    static {
        // 初始化 MIME 类型映射表
        MIME_TYPE_MAP.put("jpg", "image/jpeg");
        MIME_TYPE_MAP.put("jpeg", "image/jpeg");
        MIME_TYPE_MAP.put("png", "image/png");
        MIME_TYPE_MAP.put("gif", "image/gif");
        MIME_TYPE_MAP.put("bmp", "image/bmp");
        MIME_TYPE_MAP.put("webp", "image/webp");

        MIME_TYPE_MAP.put("txt", "text/plain");
        MIME_TYPE_MAP.put("pdf", "application/pdf");
        MIME_TYPE_MAP.put("doc", "application/msword");
        MIME_TYPE_MAP.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        MIME_TYPE_MAP.put("xls", "application/vnd.ms-excel");
        MIME_TYPE_MAP.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        MIME_TYPE_MAP.put("ppt", "application/vnd.ms-powerpoint");
        MIME_TYPE_MAP.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
        MIME_TYPE_MAP.put("zip", "application/zip");
        MIME_TYPE_MAP.put("mp3", "audio/mpeg");
        MIME_TYPE_MAP.put("mp4", "video/mp4");
        // 添加更多映射关系
    }

    public static String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
//        获取最后一个.的位置
        int lastDotIndex = fileName.lastIndexOf(".");
//        如果没有点，或者点在文件名开头，返回空字符串
        if (lastDotIndex <= 0 || lastDotIndex == fileName.length() - 1) {
            return "";
        }
//        返回文件后缀
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }

    public static String inferMimeType(String fileName) {
//        获取文件后缀
        String fileExtension = getFileExtension(fileName);
//        在映射表中获取MIME类型
        return MIME_TYPE_MAP.getOrDefault(fileExtension, "application/octet-stream");
    }

}
